﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFWS.XHandler.Core;
using JKF.Substructure;  // 这里库中有String的扩展方法
using JKF.Entities.Model;
using JKF.BusinessLayer.BLL;
using JKF.DataModule.SqlServerDAL;
using JKF.BusinessLayer;
using JKF.Entities;
using System.Data;
using JKF.DataModule;

namespace JKF.HandlerLayer.Shop
{
    public partial class ShopHandler : AHttpHandler
    {
        private static bllSHOP bllShop = new bllSHOP();
        public override void ProcessRequest()
        {
            //所有错误和异常将抛出异常.正常执行程序则在方法则返回数据
            try
            {
                this.Manager(Utils.GetActionName);
            }
            catch (Exception ex)
            {
                //将错误抛到客户端(以Json格式)
                Utils.ToClient(true, ex.Message);
                //写日志
                AppLogger.Log(ex.Message, ex);
            }
        }

        /// <summary>
        /// 添加店面
        /// </summary>
        public void InsertShop()
        {
            try
            {
                var strScr = P("moduleObj");
                var shopInfo = BuildSHOPinfoByJson(JsonSerializer.Deserialize<SHOPinfo>(strScr), false);
                var tid = shopInfo.SHOP_CODE;
                // 添加店面时，同时需要向 shop表和 dbo.SYS_USER_SHOP 表中插入数据
                string sqlInsertShop = string.Format(@"INSERT INTO dbo.SHOP(SHOP_CODE, SHOP_NAME, LINKMAN, PHONE, AREA_CODE, ADDRESS, POSTAL_CODE, MEMO, USER_CREATE, DATE_CREATE, DATE_UPDATE) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}'); ", shopInfo.SHOP_CODE, shopInfo.SHOP_NAME, shopInfo.LINKMAN, shopInfo.PHONE, shopInfo.AREA_CODE, shopInfo.ADDRESS, shopInfo.POSTAL_CODE, shopInfo.MEMO, shopInfo.USER_CREATE.ToString(), shopInfo.DATE_CREATE.ToString(), shopInfo.DATE_UPDATE.ToString());
                string result = bllShop.TransactionSQLAddBLL(shopInfo.SHOP_CODE, shopInfo.AREA_CODE, sqlInsertShop, shopInfo.USER_CREATE.ToString());
                // bllShop.Add(shopInfo);
                CacheManage.Remove("Shop_CodeOne");
                var pk = shopInfo.SHOP_CODE;
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = result, Message = "添加成功.", Data = pk }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 修改店面
        /// </summary>
        public void EditShop()
        {
            try
            {
                var strScr = P("moduleObj");
                var shopInfo = BuildSHOPinfoByJson(JsonSerializer.Deserialize<SHOPinfo>(strScr), true);
                var tid = shopInfo.SHOP_CODE;
                // 修改店面时，同时需要向 shop表和 dbo.SYS_USER_SHOP 表中更新数据 
                //bllShop.Update(shopInfo);
                string updateSql = string.Format("UPDATE dbo.SHOP SET SHOP_NAME='{0}', LINKMAN='{1}', PHONE='{2}', AREA_CODE='{3}', ADDRESS='{4}', POSTAL_CODE='{5}', MEMO='{6}',  DATE_UPDATE='{7}' WHERE SHOP_CODE='{8}'", shopInfo.SHOP_NAME, shopInfo.LINKMAN, shopInfo.PHONE, shopInfo.AREA_CODE, shopInfo.ADDRESS, shopInfo.POSTAL_CODE, shopInfo.MEMO, shopInfo.DATE_UPDATE, shopInfo.SHOP_CODE);
                string result = bllShop.TransactionSQLUpdateBLL(shopInfo.SHOP_CODE, shopInfo.AREA_CODE, updateSql, shopInfo.USER_CREATE.ToString());
                CacheManage.Remove("Shop_CodeOne");
                var pk = shopInfo.SHOP_CODE;
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = result, Message = "修改成功.", Data = pk }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 删除店面
        /// </summary>
        public void DeleteShop()
        {
            try
            {
                var shop_Code = P("id");
                // 删除店面时，同时需要向 shop表和 dbo.SYS_USER_SHOP 表中删除数据。
                // 如果一个店面下有 账户存在，需要判断后再确定删除吗？
                //string sqlDeleteShop = string.Format("DELETE dbo.SHOP WHERE SHOP_CODE='{0}'",shop_Code);
                //string sqlDeleteUser_Shop = string.Format("DELETE dbo.SYS_USER_SHOP WHERE USER_KEY='{0}' AND SHOP_CODE='{1}'");
                //bllShop.Delete(shop_Code);
                string result = bllShop.TransactionSQLDeleteBLL(shop_Code);
                CacheManage.Remove("Shop_CodeOne");
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = result, Data = shop_Code }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 从Json对象构建SHOP
        /// </summary>
        /// <param name="shopInfo">实体对象</param>
        /// <param name="isEdit">是否为编辑</param>
        /// <returns></returns>
        public SHOPinfo BuildSHOPinfoByJson(SHOPinfo shopInfo, bool isEdit)
        {//SHOP_CODE, SHOP_NAME, LINKMAN, PHONE, AREA_CODE, ADDRESS, POSTAL_CODE, MEMO, SMS_AVAIBLE, SMS_SENDED, SINGNATURE, USER_CREATE, DATE_CREATE, DATE_UPDATE
            var entity = new SHOPinfo();
            if (!isEdit) // 添加
            {
                entity.SHOP_CODE = this.AutoBuildShopCode();
            }
            else // 修改
            {
                entity.SHOP_CODE = shopInfo.SHOP_CODE;
            }
            entity.SHOP_NAME = shopInfo.SHOP_NAME;
            entity.LINKMAN = shopInfo.LINKMAN;
            entity.PHONE = shopInfo.PHONE;
            entity.AREA_CODE = shopInfo.AREA_CODE;
            entity.ADDRESS = shopInfo.ADDRESS;
            entity.POSTAL_CODE = shopInfo.POSTAL_CODE;
            entity.MEMO = shopInfo.MEMO;
            entity.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY;
            entity.DATE_CREATE = System.DateTime.Now;
            entity.DATE_UPDATE = System.DateTime.Now;
            return entity;
        }

        /// <summary>
        /// 自动生成店面编码
        /// </summary>
        /// <returns></returns>
        public string AutoBuildShopCode()
        {
            return bllShop.GetShopCodeBLL();
        }
        /// <summary>
        /// 获取店面列表数据
        /// </summary>
        public void GetShops()
        {
            var obj = new PagerList();

            int pageCount = 0;
            int rowCount = 0;
            if (P("isExport") == "1")
            {//店面名称	所在地区	联系人	联系电话	邮编	详细地址	备注

                DataTable dt = bllShop.GetShopsBLL(bllSYS_USER.CurrentUser, P("SHOP_NAME"), P("LINKMAN"), P("AREA_CODE"), P("PageIndex").ToInt32(), P("PageSize").ToInt32(), ref pageCount, ref rowCount);

                IDictionary<string, string> columns = new Dictionary<string, string>();

                columns.Add("SHOP_NAME", "店面名称");
                columns.Add("AREA_CODE", "所在地区");
                columns.Add("LINKMAN", "联系人");
                columns.Add("PHONE", "联系电话");
                columns.Add("POSTAL_CODE", "邮编");
                columns.Add("ADDRESS", "详细地址");
                columns.Add("MEMO", "备注");
                Excel.Export("店面设置", dt, columns, Response, Excel.PageType.handler);
            }
            else
            {
                obj.Entity = from a in bllShop.GetShopsBLL(bllSYS_USER.CurrentUser, P("SHOP_NAME"), P("LINKMAN"), P("AREA_CODE"), P("PageIndex").ToInt32(), P("PageSize").ToInt32(), ref pageCount, ref rowCount).AsEnumerable()
                             select new
                             {
                                 SHOP_CODE = a.Field<string>("SHOP_CODE"),
                                 SHOP_NAME = a.Field<string>("SHOP_NAME"),
                                 LINKMAN = a.Field<string>("LINKMAN"),
                                 PHONE = a.Field<string>("PHONE"),
                                 AREA_CODE = a.Field<string>("AREA_CODE"),
                                 ADDRESS = a.Field<string>("ADDRESS"),
                                 POSTAL_CODE = a.Field<string>("POSTAL_CODE"),
                                 MEMO = a.Field<string>("MEMO")
                             };

                obj.RowCount = rowCount;
                obj.PageCount = pageCount;
                ResponseJsonObject = obj;
            }
        }

        /// <summary>
        /// 根据模块shop_code获得实体模块信息
        /// </summary>
        public void GetShopByCode()
        {
            try
            {
                var scid = P("moduleKey");
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data = bllShop.GetModel(scid) }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 检查已输入店名称是否存在
        /// </summary>
        public void CheckShopName()
        {
            try
            {
                var shop_name = P("SHOP_NAME");
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data = bllShop.ExistsShopNameBLL(shop_name) }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 获取店面信息,需要加上当前用户ID条件
        /// </summary>
        public void GetAllShop()
        {
            try
            {
                var shop_code_or_name = P("term"); // 此插件提供的默认的参数名称
                string condition1 = string.Format(@" shop_code in(  select b.shop_code 
from   dbo.SYS_USER a inner join sys_user_shop b on a.user_key=b.user_key where b.user_key='{0}')", bllSYS_USER.CurrentUser.USER_KEY.ToString()); // 当前账户下的店面
                string condition2 = String.Format(" and  (SHOP_CODE LIKE '%{0}%' OR SHOP_NAME  LIKE '%{1}%')", shop_code_or_name, shop_code_or_name); // 根据用户输入的条件来进行模糊查询
                if (string.IsNullOrEmpty(shop_code_or_name.Trim()))
                {
                    condition2 = string.Format(" ");
                }

                List<SHOPinfo> shopList = bllShop.GetListArray(condition1 + condition2);
                if (shopList.Count == 0)
                {
                    shopList.Add(new SHOPinfo() { SHOP_CODE = "XXXX", SHOP_NAME = "抱歉，没有对应店面！请重新输入", AREA_CODE = "000000" });
                }
                //Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data = shopList.ToArray() }));
                Response.Write(JsonSerializer.Serialize(shopList));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 采用公服控件下拉选择
        /// </summary>
        public void SuggestGetAllShop()
        {
            try
            {
                var shop_code_or_name = P("qry"); // 此插件提供的默认的参数名称
                //页数[第一页为0]
                var page = Convert.ToInt32(Request["_pageNo"]);

                var oSuggests = new Suggests();
                var currpage = page + 1;
                var pagesize = JKF.Substructure.Utils.GetPageSize; 
                 
                string sqlWhere1 = string.Format(@" shop_code in(  select b.shop_code 
                from   dbo.SYS_USER a inner join sys_user_shop b on a.user_key=b.user_key where b.user_key='{0}')", bllSYS_USER.CurrentUser.USER_KEY.ToString()); // 当前账户下的店面
                string sqlWhere2 = String.Format(" and  (SHOP_CODE LIKE '%{0}%' OR SHOP_NAME  LIKE '%{0}%')", shop_code_or_name); // 根据用户输入的条件来进行模糊查询

                var rowCount = 0;
                var pageCount = 0;


                var ds = DataPage.GetPageInfo("SHOP", "SHOP_CODE", currpage, pagesize, "SHOP_CODE,SHOP_NAME", "SHOP_CODE", sqlWhere1 + sqlWhere2, ref pageCount, ref rowCount);

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    oSuggests._pageCnt = pageCount;
                    oSuggests.Items = new List<string>();
                    oSuggests.Items_value = new List<string>();
                    oSuggests.Data = ds;

                    foreach (DataRow item in ds.Tables[0].Rows)
                    {
                        oSuggests.Items_value.Add(item["SHOP_CODE"].ToString());//选中的值
                        oSuggests.Items.Add(string.Format("{0}", item["SHOP_NAME"]));
                    }
                }
                else
                {
                    oSuggests._pageCnt = pageCount;
                    oSuggests.Items = new List<string>();
                    oSuggests.Items_value = new List<string>();
                    oSuggests.Data = ds;
                    oSuggests.Items_value.Add("XXXX");//选中的值
                    oSuggests.Items.Add(string.Format("{0}", "抱歉，没有对应店面！请重新输入"));
                } 
                Response.Write(JsonSerializer.Serialize(oSuggests));
            }
            catch (Exception exp)
            {
                List<string> strListName = new List<string>();
                strListName.Add(exp.Message.FilterJs());
                List<string> strListValue = new List<string>();
                strListValue.Add("error");
                Response.Write(JsonSerializer.Serialize(new Suggests { Items = strListName, Items_value=strListValue }));
            }
        }

        /// <summary>
        /// 选择用户管理店铺
        /// </summary>
        [Exp2Client]
        public void SearchOwnShops()
        {
            var shopName = P("shopName");
            var linkMan = P("linkMan");
            var areaCode = P("areaCode");

            var sqlBuilder = new StringBuilder(string.Format(" shop_code in(select shop_code from sys_user_shop where user_key='{0}')", bllSYS_USER.CurrentUser.USER_KEY));

            if (!string.IsNullOrEmpty(shopName)) sqlBuilder.AppendFormat(" and shop_name like '%{0}%'", shopName.Replace("'", "''"));
            if (!string.IsNullOrEmpty(linkMan)) sqlBuilder.AppendFormat(" and LINKMAN like '%{0}%'", linkMan.Replace("'", "''"));
            if (!string.IsNullOrEmpty(areaCode))
            {
                areaCode = areaCode.TrimEnd(new[] { '0', '0' });
                if (areaCode != "")
                {
                    if (areaCode.Length != 6)
                        sqlBuilder.AppendFormat(" and area_code like '{0}%'", areaCode.Replace("'", "''"));
                    else
                        sqlBuilder.AppendFormat(" and area_code='{0}'", areaCode.Replace("'", "''"));
                }
            }

            var shops = bllShop.GetListArray(sqlBuilder.ToString());
            Response.Write(new ResponseInf()
                {
                    Success = true,
                    Data = (from SHOPinfo c in shops
                            select new
                                {
                                    SHOP_NAME = c.SHOP_NAME,
                                    SHOP_CODE = c.SHOP_CODE,
                                    LINKMAN = c.LINKMAN
                                }).ToList()
                }.ToJson());
        }
    }
}
